package com.runa.rccprotocol.dto.thtf;

import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.protocol.dto.IResponseData;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.ConcentratorRequestData;
import com.runa.rccprotocol.dto.DynamicCheckInterface;
import com.runa.rccprotocol.dto.runa.RunaConcenResponseData;

public class THTFRequestData extends ConcentratorRequestData {

    public THTFRequestData(String address) {
        super(address);
    }

    private byte[] requestData;

    private DynamicCheckInterface checkInterface;

    public void readValve(String v) {
        String dataStr = "68 00 1E b3 00000001 03B8 2A 9E 63 2B 71 0192EEEAC31F74 0302 00000000 1A 16 ";
        dataStr = dataStr.replace("B8 2A 9E 63 2B 71", address);
        dataStr = dataStr.replace("92EEEAC31F74", v);
        this.requestData = ByteUtil.hexStringToByte(dataStr);
        requestData[requestData.length - 2] = ByteUtil.sum(requestData, 1, requestData.length - 3);
        setHaveResult(true);
        this.checkInterface = data -> {
            RunaConcenResponseData responseData = (RunaConcenResponseData) data;
            if (responseData.isTailFrame()) {
                return true;
            } else {
                if (responseData.getData().get(0) instanceof ValveVO) {
                    ValveVO valveVO = (ValveVO) responseData.getData().get(0);
                    return v.equals(valveVO.getValveSerial());
                }
                return false;
            }
        };
    }

    public void houseValveOpen(String valve, int open) {
        String dataStr = "68 00 20 b3 00004F16 03B8 2A 9E 63 2B 71 0192EEEAC31F74 0602 659F7D2F 0190 C4 16";
        dataStr = dataStr.replace("B8 2A 9E 63 2B 71", address);
        dataStr = dataStr.replace("92EEEAC31F74", valve);
        dataStr = dataStr.replace("659F7D2F", String.format("%08X", System.currentTimeMillis()/1000));
        dataStr = dataStr.replace("0190 C4 16", String.format("%04X", open * 10) +" C4 16");
        this.requestData = ByteUtil.hexStringToByte(dataStr);
        requestData[requestData.length - 2] = ByteUtil.sum(requestData, 1, requestData.length - 3);
        setHaveResult(true);
    }


    @Override
    public boolean check(IResponseData data) {
        return checkInterface == null ? super.check(data) : checkInterface.check(data);
    }

    @Override
    public byte[] getData() {
        return this.requestData;
    }

}
